package cn.cloudreal.cbms.common.request;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang.StringUtils;

public class RequestWrapper extends HttpServletRequestWrapper
{

    public RequestWrapper(HttpServletRequest servletRequest)
    {
        super(servletRequest);
    }

    @Override
    public String[] getParameterValues(String parameter)
    {

        String[] values = super.getParameterValues(parameter);
        if (values == null)
        {
            return null;
        }
        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++)
        {
            encodedValues[i] = cleanXSS(values[i]);
        }
        return encodedValues;
    }

    @Override
    public String getParameter(String parameter)
    {
        String value = super.getParameter(parameter);
        if (value == null)
        {
            return null;
        }
        return cleanXSS(value);
    }

    @Override
    public String getHeader(String name)
    {
        String value = super.getHeader(name);
        if (value == null)
            return null;
        return cleanXSS(value);
    }

    @Override
    @SuppressWarnings("unchecked")
    public Map getParameterMap()
    {
        Map params = super.getParameterMap();
        Map resultMap = new HashMap();
        Iterator iterator = params.entrySet().iterator();

        do
        {
            if (!iterator.hasNext())
            {
                break;
            }

            java.util.Map.Entry entry = (java.util.Map.Entry) iterator.next();
            String name = entry.getKey().toString();
            resultMap.put(cleanXSS(name),
                    cleanXSS(((String[]) entry.getValue())[0]));

        } while (true);

        return resultMap;
    }

    private String cleanXSS(String value)
    {
        if (StringUtils.isEmpty(value))
        {
            return value;
        }

        value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        value = value.replaceAll("'", "&39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']",
                "\"\"");
        value = value.replaceAll("script", "");
        value = value.replaceAll("\u0023", "");
        return value;
    }
}
